import React, { useEffect, useState } from 'react'
import './App.css'
import { base_url, getTimeStr, store_name } from '../../util'
import classNames from 'classnames'
import { Input,Select,Row,Col,Button} from 'antd';
import 'antd/dist/antd.css'; // or 'antd/dist/antd.less'
import { HomeOutlined } from '@ant-design/icons'
const Option = Select.Option;
function App() {
  const [token, setToken] = useState<String | null>(null)
  const [workspaces, setWorkspaces] = useState<WorkspaceBaseInfo[]>([])
  const [curSelected, setCurSelected] = useState(0)

  useEffect(() => {
    // let token = localStorage.getItem("token");
    //
    // if (token) {
    //   setToken(token)
    //   fetch(`${base_url}/workspace`, {
    //     headers: { Authorization: `Bearer ${token}` },
    //   })
    //       .then(response => response.json())
    //       .then(data => {
    //         console.log(data)
    //         setWorkspaces(data.data)
    //       })
    // }
    chrome.storage.local.get(store_name, ({ token }) => {
      if (token) {
        setToken(token)
        fetch(`${base_url}/workspace`, {
          headers: { Authorization: `Bearer ${token}` },
        })
          .then(response => response.json())
          .then(data => {
            console.log(data)
            setWorkspaces(data.data)
          })
      }
    })
  }, [])

  const loginClasses = classNames('login', { hidden: token })
  const mainClasses = classNames('main', { hidden: !token })

  const [title, setTitle] = useState(
    `${getTimeStr(new Date().getTime())}学习内容`,
  )

  const handleConfirmBtn = async () => {
    //获得当前窗口的tabs
    let tabs = await chrome.tabs.query({ currentWindow: true })
    // 将所以的tabItem放入到数组中
    const tabItems: TabItem[] = []
    const filterUrl: string[] = ['http://localhost:3000']
    const urls: string[] = []

    tabs.forEach(tab => {
      console.log(tab)
      const name = tab.title ? tab.title : ''
      const url = tab.url ? tab.url : ''

      // 不保存过滤url当中的url
      let includeFilterUrl = filterUrl.find(item => url.indexOf(item) != -1)
      if (includeFilterUrl) return

      //不要重复的url
      let hasSame = tabItems.find(item => item.url == url)
      if (hasSame) return

      urls.push(url)
      tabItems.push({
        name,
        url,
      })
    })

    if (!tabItems.length) return

    _postTabs(tabItems).then(
      res => {
        console.log(res)
        window.open('http://localhost:3000/', 'target')
        // 清除掉当前的tab
        tabs.map(async tab => {
          const tid = tab.id
          if (tid) {
            await chrome.tabs.remove(tid)
          }
        })
      },
      reason => {
        console.log(reason)
      },
    )
  }

  const handleSelectChange = (selVal: string) => {
    setCurSelected(workspaces.findIndex(item => item.name == selVal))
  }

  const _postTabs = (tabs: TabItem[]) => {
    const workspaceId = workspaces[curSelected]._id
    const data = { tabs }
    return fetch(`${base_url}/tabCollection/${workspaceId}`, {
      body: JSON.stringify(data),
      headers: new Headers({
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json',
      }),
      method: 'POST',
    })
  }

  return (
    <div className="container">
      <div className={loginClasses}>
        <p className={"title"}>已有账号，去登陆</p>
        <Button style={{color:"#3EAD85",borderColor:"#3EAD85"}} className={"register"} onClick={()=> window.open('http://localhost:3000/', 'target')} >登录workSpace账号</Button>
          <p className={"title"} style={{top:"18px"}}>没有账号，去注册</p>
        <Button style={{color:"#3EAD85",borderColor:"#3EAD85",top:"15px"}} className={"register"}  onClick={()=> window.open('http://localhost:3000/', 'target')} >注册workSpace账号</Button>
      </div>

      <div className={mainClasses}>
        <div>
          <p className={"title"}>添加到workSpace</p>
          <Row >
            <Col span={8}>
              <label
                  // className="label1"
                  style={{textAlign:"left",fontWeight:"bold",width:"80px"}}>名称</label>
            </Col>
            <Col span={16}><input
                className={"input"}
                value={title}
                onChange={e => {
                  setTitle(e.target.value)
                }}
                autoFocus
            /></Col>

          </Row>
          <div style={{margin:"auto",position:"relative",top:"20px"}}>
            <Row>
              <Col span={8}>
                <label htmlFor="workspace-select" className={"label2"}>workSpace</label>
              </Col>
              <Col span={16}>
                <select
                    className={"select"}
                    placeholder={"workspace"}
                    // name="workspace"
                    id="workspace-select"
                    onChange={e => {
                      handleSelectChange(e.target.value)
                    }}


                >
                  {workspaces.map((item, index) => (
                      <option value={item.name} selected={index == 0}>
                        {item.name}
                      </option>
                  ))}
                </select>
              </Col>
            </Row>
          </div>
          <div style={{textAlign:"right",position:"relative",top:"20px"}}>
          <Row>
            <Col span={4}>
              {/*<Button>123</Button>*/}
              <HomeOutlined onClick={()=> window.open('http://localhost:3000/', 'target')} className={"home"} style={{color:"#3EAD85",top:"20px",position:"relative"}} />
            </Col>
            <Col span={8}></Col>
            <Col span={12}>
            <button  className="btn" onClick={handleConfirmBtn} style={{textAlign:"right",backgroundColor:"#3EAD85"}}>确定</button>
            </Col>
          </Row>
          </div>
        </div>
      </div>
    </div>
  )
}

export default App

// onChange={handleSelectChange}
